package gacl.servlet.study;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletConfigDemo1
 */
@WebServlet("/ServletConfigDemo1")
public class ServletConfigDemo1 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 定义ServletConfig对象来接收配置的初始化参数
	 */
	private ServletConfig config;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletConfigDemo1() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config = config;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());

		// 获取在web.xml中配置的初始化参数
		String paramval = this.config.getInitParameter("name");// 获取指定的初始化参数
		response.getWriter().print(paramval);

		response.getWriter().print("<hr/>");
		// 获取所有的初始化参数
		Enumeration<String> e = config.getInitParameterNames();
		while (e.hasMoreElements()) {
			
			String name = e.nextElement();
			String value = config.getInitParameter(name);
			response.getWriter().print(name + "=" + value + "<br/>");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
